<template>
  <div class="app-container  bg-gray">
    <el-row class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-input v-model="searchTerms.searchValue" placeholder="请输入用户名" class="search-input" @change="getData" />
              <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
              <div class="flex-1" />
              <el-button type="success" class="do-btn" @click="showDialog('添加')">添加代付系统用户</el-button>
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="name" label="用户昵称" min-width="100" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row.name?scope.row.name:'--' }}
                <span class="remarks">{{ scope.row.remarks }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机" min-width="120" header-align="center" align="center" />
            <el-table-column prop="mobile" label="负责业务员" min-width="120" header-align="center" align="center">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.sale_list" :key="index">{{ item.sales_name }}({{ item.sales_uin }})</div>
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="新拓客户" min-width="130" header-align="center" align="center">
              <template slot-scope="scope">
                限额：{{ scope.row['quota']?scope.row['quota']:'--' }}
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="存量客户" min-width="130" header-align="center" align="center">
              <template slot-scope="scope">
                限额：{{ scope.row['old_quota']?scope.row['old_quota']:'--' }}
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="指派客户" min-width="130" header-align="center" align="center">
              <template slot-scope="scope">
                限额：{{ scope.row['assign_quota']?scope.row['assign_quota']:'--' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="160" header-align="center" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button type="info" size="small" @click="showDialog('编辑', scope.row)" >编辑</el-button>
                <el-button type="danger" size="small" @click="toDelete(scope.row)" >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>
    <!--修改折扣弹窗-->
    <el-dialog :visible.sync="dialogVisible" :title="form.title" width="480px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="系统用户">
          <el-select v-model="form.admin_id" :disabled="form.title==='编辑'" placeholder="请选择系统用户" class="select" clearable filterable>
            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责业务员">
          <div class="row">
            <el-select v-model="form.sales_id" placeholder="请选择要负责的业务员" class="select" clearable filterable multiple @change="bindChangeSelect">
              <el-option v-for="item in salesList" :key="item.SalesUin" :label="item.SalesName" :value="item.SalesUin" />
            </el-select>
            <el-checkbox v-model="form.selectAll" @change="bindSelectAll">全选</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="个人邀请链接">
          <el-input v-model="form.invite_url" placeholder="请输入个人邀请链接"/>
        </el-form-item>
        <el-form-item />
        <el-divider content-position="left">新拓客户</el-divider>
        <el-form-item label="单笔支付限额">
          <el-input v-model="form.quota" type="number" placeholder="请输入单笔限额"/>
        </el-form-item>
        <el-form-item/>
        <el-divider content-position="left">存量客户</el-divider>
        <el-form-item label="单笔支付限额">
          <el-input v-model="form.old_quota" type="number" placeholder="请输入单笔限额"/>
        </el-form-item>
        <el-form-item/>
        <el-divider content-position="left">指派客户</el-divider>
        <el-form-item label="单笔支付限额">
          <el-input v-model="form.assign_quota" type="number" placeholder="请输入单笔限额"/>
        </el-form-item>
        <el-divider content-position="left">客户转账</el-divider>
        <el-form-item label="转账支付额度">
          <el-input v-model="form.transfer_quota" type="number" placeholder="请输入单笔限额"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bindSubmit('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime } from '@/utils/table'
export default {
  data() {
    return {
      searchTerms: {
        searchValue: ''
      },

      adminList: [],
      salesList: [],

      dialogVisible: false,
      form: {
        title: '添加',
        id: '',
        admin_id: '',
        sales_id: '',
        selectAll: false,
        discount: 100,
        quota: null,
        old_quota: null,
        assign_quota: null,
        transfer_quota: null,
        invite_url: ''
      },

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 300,
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },

  created() {
    this.getData();
    this.getUsersList();
    this.getSalesList();
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime,
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'tencent/getAdminData'
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize
      }
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', {url, data}).then(res => {
        this.tableData = res.data.rows
        for (let i = 0; i < res.data.rows.length; i++) {
          res.data.rows[i].sales_id = [];
          for (let j = 0; j < res.data.rows[i].sale_list.length; j++) {
            res.data.rows[i].sales_id.push(res.data.rows[i].sale_list[j].sales_uin);
          }
        }
        this.total = res.data.total
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getUsersList() {
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.adminList = res.data['list'][0]['personnel'];
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getSalesList() {
      const url = 'tencent/getDescribeSalesmans'
      const data = {
        page_no: 1,
        page_size: 10000,
        type: 1
      }
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.salesList = res.data.rows
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    bindSelectAll() {
      this.form.sales_id = [];
      if (this.form.selectAll){
        this.salesList.map((item)=>{
          this.form.sales_id.push(item.SalesUin);
        })
      }
    },

    bindChangeSelect(val) {
      if (val.length === this.salesList.length) {
        this.form.selectAll = true;
      } else {
        this.form.selectAll = false;
      }
    },

    /**
     * 修改选择客户的折扣
     */
    showDialog(title, row) {
      this.dialogVisible = true
      this.form['title'] = title
      if (row) {
        Object.assign(this.form, row)
      }
    },
    bindSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form
          if (!this.form.discount || this.form.discount === '' || this.form.discount === null) {
            this.$message.error('提交失败,请输入折扣')
            return
          }
          const sales_temp = [];
          for (let i = 0; i < data.sales_id.length; i++) {
            for (let j = 0; j < this.salesList.length; j++) {
              if (data.sales_id[i] === this.salesList[j].SalesUin) {
                sales_temp.push(this.salesList[j])
              }
            }
          }
          data.sale_list = JSON.stringify(sales_temp);
          const url = this.form.title === '添加' ? 'tencent/addAdmin' : 'tencent/updateAdmin'
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg)
            this.getData()
            this.dialogVisible = false
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        } else {
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },
    resetDialog(formName) {
      this.$refs[formName].resetFields()
    },

    toDelete(row) {
      this.$confirm('此操作将取消该系统用户代付权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'tencent/delAdmin';
        const data = {
          id: row.id
        }
        this.$store.dispatch('GetConnect', {url, data}).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员');
        })
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 15px;
    flex-wrap: wrap;
    > div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      width: 100%;
    }
    .el-select {
      padding-right: 15px;
      width: 180px;
    }
    .search-input {
      width: 240px;
    }
    .balance-input1 {
      width: 90px;
    }
    .balance-input2 {
      width: 90px;
      margin-right: 15px;
    }
    .balance-text {
      padding: 0 5px;
    }
    .do-btn {
      @extend .bg-green;
      margin-left: 6px;
    }
  }
}
.dialog {
  .content {
    text-align: center;
  }
  .row{
    display: flex;
    align-items: flex-start;
    .el-checkbox{
      margin-left: 10px;
    }
  }
}
.el-tag {
  cursor: pointer;
}
.remarks{
  font-size: 12px;
  color: $textGray;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 0px;
}
.el-select-dropdown.is-multiple .el-select-dropdown__item.selected{
  color: $panGreen;
}
</style>
